<template id="paymentRequest-handle">
  <!-- 采购付款申请抽屉 -->
  <v-navigation-drawer v-model="isUpdateDrawerShown" :permanent="isUpdateDrawerShown" fixed temporary right width="80%" class="elevation-24">
    <v-form ref="updateForm" lazy-validation>
      <!-- 抽屉标题 -->
      <v-row>
        <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">{{ticketType}}申请-处理 </span>
        <v-spacer></v-spacer>
        <!-- 抽屉操作按钮 -->
        <v-row class="justify-end mx-0 mt-6 px-8" v-if="isAllowUpdate">
          <v-btn color="success" @click="doUiAction('updateItem', '处理中')" small>处理中</v-btn>
          <v-btn color="success ml-2" @click="doUiAction('updateItem', '完成')" small>完成</v-btn>
          <v-menu v-model="isRefuseMenuShown" :close-on-content-click="false" min-width="200" offset-y>
            <template v-slot:activator="{ on, attrs }">
              <v-btn color="error ml-2" small v-bind="attrs" v-on="on">拒绝</v-btn>
            </template>
            <v-card class="pa-4">
              <v-text-field dense single-line filled v-model="ticketStatusDesc" label="拒绝原因"></v-text-field>
              <v-card-actions class="py-0">
                <v-spacer></v-spacer>
                <v-btn text @click="isRefuseMenuShown = false" x-small>取消</v-btn> 
                <v-btn color="success" text @click="doUiAction('updateItem', '拒绝')" x-small :disabled="!ticketStatusDesc">提交</v-btn>
              </v-card-actions>
            </v-card>
          </v-menu>
          <v-btn class="elevation-0 ml-2" @click="isUpdateDrawerShown = false" small>取消</v-btn>
        </v-row>
      </v-row>

      <!-- 抽屉内容 -->
      <v-expansion-panels accordion flat multiple v-model="expands">
        <v-expansion-panel
          v-for="ticket, index in ticketList" :key="index"
        >
          <v-card class="mx-4 mb-4" outlined>
            <v-expansion-panel-header>{{`【${ticket.ticketContent.paymentId}】${ticket.ticketContent.customerInfo.customerName}`}}</v-expansion-panel-header>
            <v-expansion-panel-content>

              <v-row class="mt-0">
                <template>
                  <v-col cols="12" class="d-flex">
                    <span class="jh-input-label">付款信息</span>
                    <v-spacer></v-spacer>
                    <v-chip x-small :color="constantObj.ticketStatusColor[ticket.ticketStatus]" class="ml-1" outlined>
                      {{ticket.ticketStatus}}
                    </v-chip>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-select prefix="付款账户" @change="doUiAction('paymentAccountChange', { accountName: $event, index})" v-model="ticket.ticketContent.accountInfo.accountName" item-text="accountName"
                      item-value="accountName" color="success" class="jh-v-input" :items="constantObj.paymentAccount" dense filled single-line :rules="validationRules.requireRules" :disabled="!isAllowUpdate"></v-select>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field prefix="付款金额" class="jh-v-input" dense filled single-line v-model.number="ticket.ticketContent.paymentAmount" :rules="validationRules.requireRules" type="number" :disabled="!isAllowUpdate"> </v-text-field>
                  </v-col>
                  <v-col cols="12">
                    <span class="jh-input-label mr-8 grey--text text--darken-1">付款账号：{{ticket.ticketContent.accountInfo.accountNum}}</span>
                    <span class="jh-input-label mr-8 grey--text text--darken-1">付款方式：{{ticket.ticketContent.accountInfo.accountType}}</span>
                    <span class="jh-input-label mr-8 grey--text text--darken-1">所属银行：{{ticket.ticketContent.accountInfo.accountBankName}}</span>
                    <span class="jh-input-label mr-8 grey--text text--darken-1">开户分行/支行：{{ticket.ticketContent.accountInfo.accountBranchBankName}}</span>
                  </v-col>
                </template>

                <template>
                  <v-col cols="12">
                    <span class="jh-input-label">客户信息</span>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="客户" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerName" :rules="validationRules.requireRules" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="付款账号" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerAccountNum" :rules="validationRules.requireRules" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="所属银行" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerBankName" :rules="validationRules.requireRules" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="开户分行/支行" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerBranchBankName" :rules="validationRules.requireRules" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="付款账期(天)" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerCollectionCycle" :rules="validationRules.requireRules" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="地址" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerAddress" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="联系人" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerContactPerson" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="联系电话" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerPhoneNum" disabled></v-text-field>
                  </v-col>
                  <v-col cols="12" sm="4" md="4">
                    <v-text-field class="jh-v-input" prefix="邮政编码" dense single-line filled v-model="ticket.ticketContent.customerInfo.customerPostalCode" disabled></v-text-field>
                  </v-col>
                </template>
                
                <v-col cols="12" sm="12" md="4">
                  <span class="jh-input-label">付款申请日期</span>
                  <v-menu :nudge-right="40" transition="scale-transition" offset-y min-width="auto" disabled>
                    <template v-slot:activator="{ on, attrs }">
                      <v-text-field :rules="validationRules.requireRules" dense single-line filled v-model="ticket.ticketContent.paymentRequestAt" label="" readonly v-bind="attrs" v-on="on" ></v-text-field>
                    </template>
                    <v-date-picker v-model="ticket.ticketContent.paymentRequestAt" locale="zh" ></v-date-picker>
                  </v-menu>
                </v-col>

                <v-col cols="12">
                  <span class="jh-input-label">账单信息</span>
                  <v-card elevation="0">
                    <v-data-table :headers="headers" :items="[ticket.ticketContent]" :loading="isTableLoading" hide-default-footer 
                      class="elevation-0 mt-0 mb-xs-4 flex-fill d-flex flex-column">
                      <template v-slot:item.payment-order="{ item }">
                        {{item.paymentId}}
                      </template>
                      <template v-slot:item.deduction-amount="{ item }">
                        <v-text-field prefix="¥" class="jh-v-input mr-2" dense filled single-line v-model.number="item.deductionAmount" :rules="validationRules.requireRules" type="number" disabled> </v-text-field>
                      </template>
                      <template v-slot:item.payment-total-amount="{ item }">
                        {{item.paymentTotalAmount | formatMoney}}
                      </template>
                      <template v-slot:item.payment-paid-amount="{ item }">
                        {{item.paymentPaidAmount | formatMoney}}
                      </template>
                    </v-data-table>
                  </v-card>
                </v-col>
              </v-row>
              
            </v-expansion-panel-content>
          </v-card>
        </v-expansion-panel>
      </v-expansion-panels>

    </v-form>
    <!-- 抽屉关闭按钮 -->
    <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isUpdateDrawerShown = false">
      <v-icon>mdi-close</v-icon>
    </v-btn>
  </v-navigation-drawer>
</template>

<script type="module">
  Vue.component("paymentRequest-handle", {
    template: '#paymentRequest-handle',
    props: {
    },
    data: () => ({
      validationRules: {
        requireRules: [
          v => !!v || '必填',
        ],
        numberRules: [
          v => (!isNaN(v) && parseInt(v) > 0) || '数字必填'
        ]
      },
      constantObj: {
        paymentAccount: window.constantObj.paymentAccount,
        ticketStatusColor: { '申请': 'warning', '处理中': 'blue', '拒绝': 'error', '完成': 'success', },
      },

      isTableLoading: false,
      headers: [
        {text: "账单编号", value: "payment-order", class: 'fixed', cellClass: 'fixed'},
        {text: "账单创建时间", value: "paymentCreateAt"},
        {text: "账单金额", value: "payment-total-amount"},
        {text: "已付款", value: "payment-paid-amount"},
        {text: "本次申请", value: "deduction-amount"},
      ],

      ticketIds: [],
      ticketList: [],
      actionType: '',
      expands: [],
      ticketStatusDesc: null,

      isRefuseMenuShown: false,
      isUpdateDrawerShown: false,
      updateActionData: {},

    }),
    computed: {
      ticketType() {
        const ticket = this.ticketList[0] || {}
        return ticket.ticketType;
      },
      isAllowUpdate(){
        return this.actionType === '处理';
      }
    },
    async created() {
    },
    async mounted() {
    },
    methods: {
      async doUiAction(uiActionId, uiActionData) {
        try { switch (uiActionId) {
          case 'startUpdateItem':
            await this.prepareUpdateFormData(uiActionData);
            await this.getTicketData();
            await this.openUpdateDrawer();
            break;
          case 'updateItem':
            await this.prepareUpdateValidate();
            await this.confirmUpdateItemDialog();
            await this.prepareDoUpdateItem(uiActionData);
            await this.doUpdateItem();
            await this.closeUpdateDrawer();
            break;
          case 'paymentAccountChange':
            await this.setTicketPaymentAccount(uiActionData);
            break;
          default:
            console.error("[doUiAction] uiActionId not find", { uiActionId });
            break;
        }} catch (error) { await window.jhMask.hide(); throw error; }
      },

      // ---------- 初始化数据 uiAction >>>>>>>>>> --------
      async prepareUpdateFormData({ ticketIds=[], actionType }) {
        this.ticketIds = ticketIds;
        this.actionType = actionType;
      },
      async getTicketData() {
        this.isTableLoading = true;
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'ticketManagement',
              actionId: 'selectItemList',
              actionData: {},
              whereIn: { ticketId: this.ticketIds },
              orderBy: [{ column: 'idSequence', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;

        this.ticketList = _.map(rows, item => {
          const ticketContent = item.ticketContent ? JSON.parse(item.ticketContent) : JSON.parse(item.ticketContentRequest);
          return {
            ...item,
            ticketContent: {
              ...ticketContent,
              accountInfo: ticketContent.accountInfo ||  _.cloneDeep(this.constantObj.paymentAccount[0]),
              paymentAmount: ticketContent.paymentAmount ||  ticketContent.deductionAmount 
            }
          }
        });
        this.expands = _.map(this.ticketList, (item, index) => index);
        this.isTableLoading = false;
      },
      async openUpdateDrawer() {
        this.isUpdateDrawerShown = true;
      },
      // ---------- <<<<<<<<<<< 初始化数据 uiAction ---------

      // ---------- 修改数据 uiAction >>>>>>>>>> --------
      async prepareUpdateValidate() {
        if (await this.$refs.updateForm.validate()) {
          return true;
        }
        await window.vtoast.fail("请完善表单信息");
        throw new Error("请完善表单信息")
      },
      async confirmUpdateItemDialog() {
        if (await window.confirmDialog({title: "提交", content: "确定提交吗？"}) === false) {
          throw new Error("[confirmUpdateFormDialog] 否");
        }
      },
      prepareDoUpdateItem(funData) {
        this.updateActionData = _.map(this.ticketList, item => {
          return {
            ...item,
            ticketStatus: funData,
            ticketStatusDesc: this.ticketStatusDesc
          };
        })
      },
      async doUpdateItem() {
        await window.vtoast.loading("提交数据");
        await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'paymentTicketRequest',
              actionId: 'handlePaymentRequest',
              actionData: { dataList: this.updateActionData },
            }
          }
        })
        await window.vtoast.success("提交成功");
      },
      async closeUpdateDrawer() {
        this.isUpdateDrawerShown = false;
        this.updateActionData = null;
        this.$emit("success");
      },
      // ---------- <<<<<<<<<<< 修改数据 uiAction ---------

      // ---------- 表单change uiAction >>>>>>>>>> --------
      async setTicketPaymentAccount(funData) {
        const { accountName, index } = funData;
        this.ticketList[index].ticketContent.accountInfo = _.cloneDeep(_.find(this.constantObj.paymentAccount, { accountName }));
      },
      // ---------- <<<<<<<<<<< 表单change uiAction ---------
    }
  })
</script>
<style>

</style>
